<?php

namespace Home\Controller;
use Think\Controller; 
class PurchaseController extends Controller {
	
	public function __construct(){
		parent::__construct();
		
		if(empty($_SESSION['user']))
		{
			$this->error('对不起,您还没有登录!请先登录!', U('Login/login'), 1);
		}
	}
	
	public function strtolower_x(){
		$data= M('order_info')->query('select sku,id from order_info');
		//var_dump($data);
		foreach($data as $v){
			$where = "id = ".$v['id'];
			
			M("order_info")->where($where)->save(array('sku'=>strtoupper($v['sku'])));
		}
	}
	
	public function purchase(){
		$name = $_SESSION['user'];
		$account = M("account")->field('purchase')->where(array('username'=>$name))->find();
		$type = $account['purchase'];
		if($type=='2'){
			$name = $_SESSION['user'];
			$where = "  (status = '2' or status='3') and buyer='$name' and sales_return ='' and alsobuy >0";

			$purchase_list = M('order_info')->where($where)->order('order_number')->order('supplier asc,sku asc')->select();
			foreach($purchase_list as $key=>$val){	
				$where = " buyer='".$name."' and sku='".$val['sku']."' and sales_return=''  and (status='2' or status='3') and alsobuy>0";

				$quantity = M('order_info')->where($where)->order('supplier asc,sku asc')->SUM('quantity');
				
				$cumulative_quantity = M('order_info')->where($where)->order('supplier asc,sku asc')->SUM('cumulative_quantity');
				$alsobuy= M('order_info')->where($where)->order('supplier asc,sku asc')->SUM('alsobuy');
				
				$purchase_list[$key]['count'] = $alsobuy;

				$product_price = M('product')->field('cost_price')->where(array('sku'=>$val['sku']))->find();
				$purchase_list[$key]['cost_price'] = $product_price['cost_price'];
			}
		
		
		}else{
			$search_buyer = I("post.buyer","","htmlspecialchars")?I("post.buyer","","htmlspecialchars"):'';
			if(empty($search_buyer)){
				$where = " (status = '2' or status='3')  and sales_return ='' and alsobuy >0";
				
				$purchase = M('order_info')->where($where)->group('buyer')->select();
				foreach($purchase as $key=>$val){
					$where = " (status = '2' or status='3') and buyer='".$val['buyer']."' and sales_return ='' and alsobuy >0";
					
					$purchase_list = M('order_info')->where($where)->order('order_number')->order('supplier asc,sku asc')->select();
					foreach($purchase_list as $k=>$v){
						$where = " buyer='".$v['buyer']."' and sku='".$v['sku']."' and sales_return='' and supplier='".$v['supplier']."' and (status='2' or status='3') and alsobuy>0";
						$quantity= M('order_info')->where($where)->order('supplier asc,sku asc')->SUM('quantity');
						
						$cumulative_quantity= M('order_info')->where($where)->order('supplier asc,sku asc')->SUM('cumulative_quantity');
						$alsobuy= M('order_info')->where($where)->order('supplier asc,sku asc')->SUM('alsobuy');
						//echo M('order_info')->getLastSql().'<br/>';
						$purchase_list[$k]['count'] = $alsobuy;
						$product_price = M('product')->field('cost_price')->where(array('sku'=>$v['sku']))->find();
						$purchase_list[$k]['cost_price'] = $product_price['cost_price'];
					}
					
					$purchase[$key] = $purchase_list;	
					
				}
			}else{

				$where = " (status = '2' or status='3') and buyer='$search_buyer' and sales_return ='' and alsobuy >0";
				$purchase[] = M('order_info')->where(array('buyer'=>$search_buyer))->find();

				foreach($purchase as $k=>$v){
					$purchase_list = M('order_info')->where($where)->order('order_number')->order('supplier asc,sku asc')->select();
					
					foreach($purchase_list as $key=>$val){	
						$where = " buyer='".$search_buyer."' and sku='".$val['sku']."' and sales_return=''  and (status='2' or status='3') and alsobuy>0";
						$quantity = M('order_info')->where($where)->order('supplier asc,sku asc')->SUM('quantity');
						
						$cumulative_quantity = M('order_info')->where($where)->order('supplier asc,sku asc')->SUM('cumulative_quantity');
						$alsobuy = M('order_info')->where($where)->order('supplier asc,sku asc')->SUM('alsobuy');
						$purchase_list[$key]['count'] = $alsobuy;
						$product_price = M('product')->field('cost_price')->where(array('sku'=>$val['sku']))->find();
						$purchase_list[$key]['cost_price'] = $product_price['cost_price'];
					}

					$purchase[$k] = $purchase_list;	

				}
			}

			$where = " sales_return='' and (status='2' or status='3')";
			$buyer_list = M('order_info')->field('buyer')->where($where)->group('buyer')->select();
			
			}
		
		if(I("create","","htmlspecialchars")){
			$buyer = I('buyer','','htmlspecialchars');
			
			$where = " (buyer='$buyer' and (status='2' or status='3') and is_create='' and porder_number='' and sales_return='' and alsobuy>0) or (buyer='$buyer' and (status='2' or status='3') and is_create='' and porder_number ='NULL' and sales_return='' and alsobuy>0)  or (buyer='$buyer' and (status='2' or status='3') and is_create='' and porder_number is null and sales_return='' and alsobuy>0)";
			
			$data = M("order_info")->field('buyer,salesman,order_number,alsobuy,order_date,remarks')->where($where)->order('supplier asc,sku asc')->select();
			
			$count_data = count($data);
			$data[0]['count'] = count($data);
			if($count_data<1){$this->error('无法重复导出数据，请在采购单处理页面跟进');}	
			$where = " buyer='".$buyer."' and (status='2' or status='3') and is_create='' and sales_return='' and alsobuy>0";

			$supplier = M("order_info")->field('supplier')->where($where)->group('supplier')->order('supplier asc,sku asc')->select();
			foreach($supplier as $k=>$v){
				$sum += count($supplier_sum);
				$where = " buyer='".$buyer."' and (status='2' or status='3') and is_create='' and sales_return='' and supplier='".$v['supplier']."' and alsobuy>0";
				$supplier_sum = M("order_info")->field('supplier')->where($where)->order('supplier asc,sku asc')->select();
				$data[$sum]['supplier'] = $v['supplier'];
				$data[$sum]['supplier_sum'] = count($supplier_sum);
				
			
			}
			
			$where = " buyer='".$buyer."' and (status='2' or status='3') and is_create='' and sales_return='' and alsobuy>0";

			$sku = M("order_info")->field('sku,main_pic,cost_price,supplier,alsobuy')->where($where)->group('sku')->order('supplier asc,sku asc')->select();
			foreach($sku as $k1=>$v){
				$sum_sku += count($sku_sum);
				$where = " buyer='".$buyer."' and (status='2' or status='3') and is_create='' and sales_return='' and sku='".$v['sku']."' and alsobuy>0";
				$sku_sum = M("order_info")->field('sku,main_pic,cost_price')->where($where)->order('supplier asc,sku asc')->select();
				$data[$sum_sku]['sku'] = $v['sku'];
				$data[$sum_sku]['sku_sum'] = count($sku_sum);
				$data[$sum_sku]['main_pic'] = $v['_pic'];
				$data[$sum_sku]['pic_sum'] = count($sku_sum);
				$data[$sum_sku]['cost_price'] = $v['cost_price'];
				$data[$sum_sku]['price_sum'] = count($sku_sum);
				
				$where = " buyer='".$buyer."' and (status='2' or status='3') and is_create='' and sales_return='' and  sku='".$v['sku']."' and supplier='".$v['supplier']."' and alsobuy>0";
	
				$total = M("order_info")->where($where)->order('supplier asc,sku asc')->SUM('alsobuy');
				
				$data[$sum_sku]['total_quantity'] = $total;
				
				$data[$sum_sku]['total_sum'] = count($total);
			}
			
		import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Worksheet.Drawing");
        import("Org.Util.PHPExcel.Writer.Excel2007");
		import("Org.Util.PHPExcel.Style.NumberFormat");
		import("Org.Util.PHPExcel.Style.Alignment");
		import("Org.Util.PHPExcel.Style.Color");
        $objPHPExcel = new \PHPExcel();
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
    	
        $objActSheet = $objPHPExcel->getActiveSheet();
        
        // 水平居中（位置很重要，建议在最初始位置）
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('B')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('C')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('D')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('E')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('F')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('G')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('H')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('I')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('J')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('K')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        

        // 设置个表格宽度
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(10);
        
        // 垂直居中
        $objPHPExcel->getActiveSheet()->getStyle('A')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('B')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('C')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('D')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('E')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('F')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('G')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('H')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('I')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('J')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('K')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        
		//合并列单元
		//设置宽度
		//$objActSheet->getColumnDimension('B')->setAutoSize(true);
		$objActSheet->getColumnDimension('A')->setWidth(10);
		$objActSheet->getColumnDimension('B')->setWidth(10);
		$objActSheet->getColumnDimension('C')->setWidth(15);
		$objActSheet->getColumnDimension('D')->setWidth(18);
		$objActSheet->getColumnDimension('E')->setWidth(10);
		$objActSheet->getColumnDimension('F')->setWidth(10);
		$objActSheet->getColumnDimension('G')->setWidth(10);
		$objActSheet->getColumnDimension('H')->setWidth(10);
		$objActSheet->getColumnDimension('I')->setWidth(10);
		$objActSheet->getColumnDimension('J')->setWidth(10);
		$objActSheet->getColumnDimension('K')->setWidth(10);
		
		
		//$objActSheet->getRowDimension('A')->setRowHeight(30);
        $objActSheet->setCellValue('A1', '采购员');
		$objActSheet->setCellValue('B1', '供应商');
		$objActSheet->setCellValue('C1', 'SKU');
		$objActSheet->setCellValue('D1', '产品图片');
		$objActSheet->setCellValue('E1', '采购单价');
		$objActSheet->setCellValue('F1', '总数量');
		$objActSheet->setCellValue('G1', '业务员');
		$objActSheet->setCellValue('H1', '订单号');
		$objActSheet->setCellValue('I1', '产品数量');
		$objActSheet->setCellValue('J1', '历史订单');
		$objActSheet->setCellValue('K1', '备注');
        // 处理表数据
        foreach($data as $key=>$v){
           	$k=2;
			$k+=$key;
			if($v['count']){
				$objPHPExcel->getActiveSheet()->mergeCells('A'.$k.':A'.($v['count']+1));
				$objActSheet->setCellValue('A'.$k, $v['buyer']); 
				
			}
			if($v['supplier_sum']){
				$objPHPExcel->getActiveSheet()->mergeCells('B'.$k.':B'.($v['supplier_sum']+$k-1));
				$objActSheet->setCellValue('B'.$k, $v['supplier']); 
			}
			if($v['sku_sum']){
				$objPHPExcel->getActiveSheet()->mergeCells('C'.$k.':C'.($v['sku_sum']+$k-1));
				$objActSheet->setCellValue('C'.$k, $v['sku']); 
			}
			
			
			if($v['pic_sum']){
				
				$objPHPExcel->getActiveSheet()->mergeCells('D'.$k.':D'.($v['pic_sum']+$k-1));
				
				$dir = "public/images/".$v['sku']; // 文件夹的名称
				$file = array();
				if (is_dir($dir)){
				  if ($dh = opendir($dir)){
					while (($file[] = readdir($dh)) !== false){
					}
					closedir($dh);
				  }
				}
				if( in_array("B.jpg",$file) || in_array("B.jpeg",$file) || in_array("B.png",$file) || in_array("B.gif",$file) ||  in_array("B.JPG",$file) || in_array("B.JPEG",$file) || in_array("B.PNG",$file) || in_array("B.GIF",$file)){
					$objActSheet->getRowDimension('D'.$k)->setRowHeight(80);
					$objDrawing[$k] = new \PHPExcel_Worksheet_Drawing();
					$v['sku'] = trim($v['sku'],' ');
					$path = $v['sku'].'/B.jpg';
					$objDrawing[$k]->setPath('Public/images/'.$path);
					// 设置宽度高度
					$Height = '110';
					$Width = "110";
					$objDrawing[$k]->setHeight($Height.'pt');//照片高度
					$objDrawing[$k]->setWidth($Width.'pt'); //照片宽度
					/*设置图片要插入的单元格*/
					$objDrawing[$k]->setCoordinates('D'.$k);
					// 图片偏移距离
					
					$x = 10;
					$y = $Height/$v['pic_sum']+15;
					$objDrawing[$k]->setOffsetX(10);
					$objDrawing[$k]->setOffsetY(5);
					$objDrawing[$k]->setWorksheet($objPHPExcel->getActiveSheet()); 
					}else{
						$objActSheet->setCellValue('D'.$k, '图片丢失'); 
				}
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('D')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        
        $objPHPExcel->getActiveSheet()->getStyle('D')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
			}
            
			
			
				
			if($v['price_sum']){
				
				$price_sum =$k+$v['price_sum'];
				$objPHPExcel->getActiveSheet()->mergeCells('E'.$k.':E'.($v['price_sum']+$k-1));
				$objActSheet->setCellValue('E'.$k, $v['cost_price']); 
			}
           
				
			
			if($v['sku_sum']){
				$objPHPExcel->getActiveSheet()->mergeCells('F'.$k.':F'.($v['sku_sum']+$k-1));
				$objActSheet->setCellValue('F'.$k, $v['total_quantity']); 
			}
			
			$objActSheet->setCellValue('G'.$k, $v['salesman']); 
			$objActSheet->setCellValue('H'.$k, $v['order_number']);
			$objActSheet->setCellValue('I'.$k, $v['alsobuy']); 
			$objActSheet->getRowDimension($k)->setRowHeight(90);
			$arr_time = explode(' ',$v['order_date']);
			$time = $arr_time[0];
			$now_time = date('Y-m-d',time());
			if($time != $now_time){
				$objActSheet->setCellValue('J'.$k, "***"); 
			}else{
				$objActSheet->setCellValue('J'.$k, " "); 
			}
			
			
			if(empty($v['remarks'])){
				$objActSheet->setCellValue('K'.$k, "　"); 
			}else{
				$objActSheet->setCellValue('K'.$k, $v['remarks']); 
			}
			
			
			
        }
        $fileName = '采购明细表';
        $date1 = date("Y-m-d",time());
        $fileName .= "_{$date1}.xls";

        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        // $objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        // END    
		
		$porder_number = $this->StrOrderOne();
		$where = " buyer='".$buyer."' and (status='2' or status='3') and is_create='' and sales_return='' and alsobuy>0";
		//array('buyer'=>$buyer,'status'=>'2','is_create'=>'')
		$result = M("order_info")->where($where)->save(array('is_create'=>'1','create_time'=>date('Y-m-d H:i:s'),'porder_number'=>$porder_number));
		
		}
		
		$now_time = date(('Y-m-d'),time());
		$time = date(('Y-m-d'),time());
		$now_start = $now_time. " 00:00:00";
		$now_end = $now_time. " 59:59:59";
		$this->assign("now_end",$now_end);
		$this->assign("now_start",$now_start);
		
		$this->assign("sum",sizeof($purchase_list));
		$this->assign("type",$type);
		$this->assign("count",$count);
		$this->assign("create_time",$create_time);
		$this->assign("purchase_list",$purchase_list);
		$this->assign("purchase_list2",$purchase);
		$this->assign("buyer_list",$buyer_list);
		$this->display();
	}
	//缺货产品
	// public function purchase(){
	// 	$name = $_SESSION['user'];
	// 	$account = M("account")->field('purchase')->where(array('username'=>$name))->find();
	// 	$type = $account['purchase'];
	// 	if($type=='2'){
	// 		$name = $_SESSION['user'];
	// 		$where = "  (status = '2' or status='3') and buyer='$name' and sales_return ='' and alsobuy >0";

	// 		$purchase_list = M('order_info')->where($where)->order('order_number')->order('supplier asc,sku asc')->select();
	// 		foreach($purchase_list as $key=>$val){	
	// 			$where = " buyer='".$name."' and sku='".$val['sku']."' and sales_return=''  and (status='2' or status='3') and alsobuy>0";

	// 			$quantity = M('order_info')->where($where)->order('supplier asc,sku asc')->SUM('quantity');
				
	// 			$cumulative_quantity = M('order_info')->where($where)->order('supplier asc,sku asc')->SUM('cumulative_quantity');
	// 			$alsobuy= M('order_info')->where($where)->order('supplier asc,sku asc')->SUM('alsobuy');
				
	// 			$purchase_list[$key]['count'] = $alsobuy;

	// 			$product_price = M('product')->field('cost_price')->where(array('sku'=>$val['sku']))->find();
	// 			$purchase_list[$key]['cost_price'] = $product_price['cost_price'];
	// 		}
		
		
	// 	}else{
	// 		$search_buyer = I("post.buyer","","htmlspecialchars")?I("post.buyer","","htmlspecialchars"):'';
	// 		if(empty($search_buyer)){
	// 			$where = " (status = '2' or status='3')  and sales_return ='' and alsobuy >0";
				
	// 			$purchase = M('order_info')->where($where)->group('buyer')->select();
	// 			foreach($purchase as $key=>$val){
	// 				$where = " (status = '2' or status='3') and buyer='".$val['buyer']."' and sales_return ='' and alsobuy >0";
					
	// 				$purchase_list = M('order_info')->where($where)->order('order_number')->order('supplier asc,sku asc')->select();
	// 				foreach($purchase_list as $k=>$v){
	// 					$where = " buyer='".$v['buyer']."' and sku='".$v['sku']."' and sales_return='' and supplier='".$v['supplier']."' and (status='2' or status='3') and alsobuy>0";
	// 					$quantity= M('order_info')->where($where)->order('supplier asc,sku asc')->SUM('quantity');
						
	// 					$cumulative_quantity= M('order_info')->where($where)->order('supplier asc,sku asc')->SUM('cumulative_quantity');
	// 					$alsobuy= M('order_info')->where($where)->order('supplier asc,sku asc')->SUM('alsobuy');
	// 					//echo M('order_info')->getLastSql().'<br/>';
	// 					$purchase_list[$k]['count'] = $alsobuy;
	// 					$product_price = M('product')->field('cost_price')->where(array('sku'=>$v['sku']))->find();
	// 					$purchase_list[$k]['cost_price'] = $product_price['cost_price'];
	// 				}
					
	// 				$purchase[$key] = $purchase_list;	
					
	// 			}
	// 		}else{

	// 			$where = " (status = '2' or status='3') and buyer='$search_buyer' and sales_return ='' and alsobuy >0";
	// 			$purchase[] = M('order_info')->where(array('buyer'=>$search_buyer))->find();

	// 			foreach($purchase as $k=>$v){
	// 				$purchase_list = M('order_info')->where($where)->order('order_number')->order('supplier asc,sku asc')->select();
					
	// 				foreach($purchase_list as $key=>$val){	
	// 					$where = " buyer='".$search_buyer."' and sku='".$val['sku']."' and sales_return=''  and (status='2' or status='3') and alsobuy>0";
	// 					$quantity = M('order_info')->where($where)->order('supplier asc,sku asc')->SUM('quantity');
						
	// 					$cumulative_quantity = M('order_info')->where($where)->order('supplier asc,sku asc')->SUM('cumulative_quantity');
	// 					$alsobuy = M('order_info')->where($where)->order('supplier asc,sku asc')->SUM('alsobuy');
	// 					$purchase_list[$key]['count'] = $alsobuy;
	// 					$product_price = M('product')->field('cost_price')->where(array('sku'=>$val['sku']))->find();
	// 					$purchase_list[$key]['cost_price'] = $product_price['cost_price'];
	// 				}

	// 				$purchase[$k] = $purchase_list;	

	// 			}
	// 		}

	// 		$where = " sales_return='' and (status='2' or status='3')";
	// 		$buyer_list = M('order_info')->field('buyer')->where($where)->group('buyer')->select();
			
	// 		}
		
	// 	if(I("create","","htmlspecialchars")){
	// 		$buyer = I('buyer','','htmlspecialchars');
			
	// 		$where = " (buyer='$buyer' and (status='2' or status='3') and is_create='' and porder_number='' and sales_return='' and alsobuy>0) or (buyer='$buyer' and (status='2' or status='3') and is_create='' and porder_number ='NULL' and sales_return='' and alsobuy>0)  or (buyer='$buyer' and (status='2' or status='3') and is_create='' and porder_number is null and sales_return='' and alsobuy>0)";
			
	// 		$data = M("order_info")->field('buyer,salesman,order_number,alsobuy,order_date,remarks')->where($where)->order('supplier asc,sku asc')->select();
			
	// 		$count_data = count($data);
	// 		$data[0]['count'] = count($data);
	// 		if($count_data<1){$this->error('无法重复导出数据，请在采购单处理页面跟进');}	
	// 		$where = " buyer='".$buyer."' and (status='2' or status='3') and is_create='' and sales_return='' and alsobuy>0";

	// 		$supplier = M("order_info")->field('supplier')->where($where)->group('supplier')->order('supplier asc,sku asc')->select();
	// 		foreach($supplier as $k=>$v){
	// 			$sum += count($supplier_sum);
	// 			$where = " buyer='".$buyer."' and (status='2' or status='3') and is_create='' and sales_return='' and supplier='".$v['supplier']."' and alsobuy>0";
	// 			$supplier_sum = M("order_info")->field('supplier')->where($where)->order('supplier asc,sku asc')->select();
	// 			$data[$sum]['supplier'] = $v['supplier'];
	// 			$data[$sum]['supplier_sum'] = count($supplier_sum);
				
			
	// 		}
			
	// 		$where = " buyer='".$buyer."' and (status='2' or status='3') and is_create='' and sales_return='' and alsobuy>0";

	// 		$sku = M("order_info")->field('sku,main_pic,cost_price,supplier,alsobuy')->where($where)->group('sku')->order('supplier asc,sku asc')->select();
	// 		foreach($sku as $k1=>$v){
	// 			$sum_sku += count($sku_sum);
	// 			$where = " buyer='".$buyer."' and (status='2' or status='3') and is_create='' and sales_return='' and sku='".$v['sku']."' and alsobuy>0";
	// 			$sku_sum = M("order_info")->field('sku,main_pic,cost_price')->where($where)->order('supplier asc,sku asc')->select();
	// 			$data[$sum_sku]['sku'] = $v['sku'];
	// 			$data[$sum_sku]['sku_sum'] = count($sku_sum);
	// 			$data[$sum_sku]['main_pic'] = $v['_pic'];
	// 			$data[$sum_sku]['pic_sum'] = count($sku_sum);
	// 			$data[$sum_sku]['cost_price'] = $v['cost_price'];
	// 			$data[$sum_sku]['price_sum'] = count($sku_sum);
				
	// 			$where = " buyer='".$buyer."' and (status='2' or status='3') and is_create='' and sales_return='' and  sku='".$v['sku']."' and supplier='".$v['supplier']."' and alsobuy>0";
	
	// 			$total = M("order_info")->where($where)->order('supplier asc,sku asc')->SUM('alsobuy');
				
	// 			$data[$sum_sku]['total_quantity'] = $total;
				
	// 			$data[$sum_sku]['total_sum'] = count($total);
	// 		}
			
	// 	import("Org.Util.PHPExcel");
 //        import("Org.Util.PHPExcel.Worksheet.Drawing");
 //        import("Org.Util.PHPExcel.Writer.Excel2007");
	// 	import("Org.Util.PHPExcel.Style.NumberFormat");
	// 	import("Org.Util.PHPExcel.Style.Alignment");
	// 	import("Org.Util.PHPExcel.Style.Color");
 //        $objPHPExcel = new \PHPExcel();
 //        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
    	
 //        $objActSheet = $objPHPExcel->getActiveSheet();
        
 //        // 水平居中（位置很重要，建议在最初始位置）
 //        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
 //        $objPHPExcel->setActiveSheetIndex(0)->getStyle('B')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
 //        $objPHPExcel->setActiveSheetIndex(0)->getStyle('C')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
 //        $objPHPExcel->setActiveSheetIndex(0)->getStyle('D')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
 //        $objPHPExcel->setActiveSheetIndex(0)->getStyle('E')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
 //        $objPHPExcel->setActiveSheetIndex(0)->getStyle('F')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
 //        $objPHPExcel->setActiveSheetIndex(0)->getStyle('G')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
 //        $objPHPExcel->setActiveSheetIndex(0)->getStyle('H')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
 //        $objPHPExcel->setActiveSheetIndex(0)->getStyle('I')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
 //        $objPHPExcel->setActiveSheetIndex(0)->getStyle('J')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
 //        $objPHPExcel->setActiveSheetIndex(0)->getStyle('K')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        

 //        // 设置个表格宽度
 //        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
 //        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(10);
 //        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(10);
 //        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(25);
 //        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
 //        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(10);
 //        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(10);
 //        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(10);
 //        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(10);
 //        $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(10);
 //        $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(10);
        
 //        // 垂直居中
 //        $objPHPExcel->getActiveSheet()->getStyle('A')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
 //        $objPHPExcel->getActiveSheet()->getStyle('B')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
 //        $objPHPExcel->getActiveSheet()->getStyle('C')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
 //        $objPHPExcel->getActiveSheet()->getStyle('D')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
 //        $objPHPExcel->getActiveSheet()->getStyle('E')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
 //        $objPHPExcel->getActiveSheet()->getStyle('F')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
 //        $objPHPExcel->getActiveSheet()->getStyle('G')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
 //        $objPHPExcel->getActiveSheet()->getStyle('H')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
 //        $objPHPExcel->getActiveSheet()->getStyle('I')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
 //        $objPHPExcel->getActiveSheet()->getStyle('J')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
 //        $objPHPExcel->getActiveSheet()->getStyle('K')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        
	// 	//合并列单元
	// 	//设置宽度
	// 	//$objActSheet->getColumnDimension('B')->setAutoSize(true);
	// 	$objActSheet->getColumnDimension('A')->setWidth(10);
	// 	$objActSheet->getColumnDimension('B')->setWidth(10);
	// 	$objActSheet->getColumnDimension('C')->setWidth(15);
	// 	$objActSheet->getColumnDimension('D')->setWidth(18);
	// 	$objActSheet->getColumnDimension('E')->setWidth(10);
	// 	$objActSheet->getColumnDimension('F')->setWidth(10);
	// 	$objActSheet->getColumnDimension('G')->setWidth(10);
	// 	$objActSheet->getColumnDimension('H')->setWidth(10);
	// 	$objActSheet->getColumnDimension('I')->setWidth(10);
	// 	$objActSheet->getColumnDimension('J')->setWidth(10);
	// 	$objActSheet->getColumnDimension('K')->setWidth(10);
		
		
	// 	//$objActSheet->getRowDimension('A')->setRowHeight(30);
 //        $objActSheet->setCellValue('A1', '采购员');
	// 	$objActSheet->setCellValue('B1', '供应商');
	// 	$objActSheet->setCellValue('C1', 'SKU');
	// 	$objActSheet->setCellValue('D1', '产品图片');
	// 	$objActSheet->setCellValue('E1', '采购单价');
	// 	$objActSheet->setCellValue('F1', '总数量');
	// 	$objActSheet->setCellValue('G1', '业务员');
	// 	$objActSheet->setCellValue('H1', '订单号');
	// 	$objActSheet->setCellValue('I1', '产品数量');
	// 	$objActSheet->setCellValue('J1', '历史订单');
	// 	$objActSheet->setCellValue('K1', '备注');
 //        // 处理表数据
 //        foreach($data as $key=>$v){
 //           	$k=2;
	// 		$k+=$key;
	// 		if($v['count']){
	// 			$objPHPExcel->getActiveSheet()->mergeCells('A'.$k.':A'.($v['count']+1));
	// 			$objActSheet->setCellValue('A'.$k, $v['buyer']); 
				
	// 		}
	// 		if($v['supplier_sum']){
	// 			$objPHPExcel->getActiveSheet()->mergeCells('B'.$k.':B'.($v['supplier_sum']+$k-1));
	// 			$objActSheet->setCellValue('B'.$k, $v['supplier']); 
	// 		}
	// 		if($v['sku_sum']){
	// 			$objPHPExcel->getActiveSheet()->mergeCells('C'.$k.':C'.($v['sku_sum']+$k-1));
	// 			$objActSheet->setCellValue('C'.$k, $v['sku']); 
	// 		}
			
			
	// 		if($v['pic_sum']){
				
	// 			$objPHPExcel->getActiveSheet()->mergeCells('D'.$k.':D'.($v['pic_sum']+$k-1));
				
	// 			$dir = "public/images/".$v['sku']; // 文件夹的名称
	// 			$file = array();
	// 			if (is_dir($dir)){
	// 			  if ($dh = opendir($dir)){
	// 				while (($file[] = readdir($dh)) !== false){
	// 				}
	// 				closedir($dh);
	// 			  }
	// 			}
	// 			if( in_array("B.jpg",$file) || in_array("B.jpeg",$file) || in_array("B.png",$file) || in_array("B.gif",$file) ||  in_array("B.JPG",$file) || in_array("B.JPEG",$file) || in_array("B.PNG",$file) || in_array("B.GIF",$file)){
	// 				$objActSheet->getRowDimension('D'.$k)->setRowHeight(80);
	// 				$objDrawing[$k] = new \PHPExcel_Worksheet_Drawing();
	// 				$v['sku'] = trim($v['sku'],' ');
	// 				$path = $v['sku'].'/B.jpg';
	// 				$objDrawing[$k]->setPath('Public/images/'.$path);
	// 				// 设置宽度高度
	// 				$Height = '110';
	// 				$Width = "110";
	// 				$objDrawing[$k]->setHeight($Height.'pt');//照片高度
	// 				$objDrawing[$k]->setWidth($Width.'pt'); //照片宽度
	// 				/*设置图片要插入的单元格*/
	// 				$objDrawing[$k]->setCoordinates('D'.$k);
	// 				// 图片偏移距离
					
	// 				$x = 10;
	// 				$y = $Height/$v['pic_sum']+15;
	// 				$objDrawing[$k]->setOffsetX(10);
	// 				$objDrawing[$k]->setOffsetY(5);
	// 				$objDrawing[$k]->setWorksheet($objPHPExcel->getActiveSheet()); 
	// 				}else{
	// 					$objActSheet->setCellValue('D'.$k, '图片丢失'); 
	// 			}
 //        $objPHPExcel->setActiveSheetIndex(0)->getStyle('D')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        
 //        $objPHPExcel->getActiveSheet()->getStyle('D')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
	// 		}
            
			
			
				
	// 		if($v['price_sum']){
				
	// 			$price_sum =$k+$v['price_sum'];
	// 			$objPHPExcel->getActiveSheet()->mergeCells('E'.$k.':E'.($v['price_sum']+$k-1));
	// 			$objActSheet->setCellValue('E'.$k, $v['cost_price']); 
	// 		}
           
				
			
	// 		if($v['sku_sum']){
	// 			$objPHPExcel->getActiveSheet()->mergeCells('F'.$k.':F'.($v['sku_sum']+$k-1));
	// 			$objActSheet->setCellValue('F'.$k, $v['total_quantity']); 
	// 		}
			
	// 		$objActSheet->setCellValue('G'.$k, $v['salesman']); 
	// 		$objActSheet->setCellValue('H'.$k, $v['order_number']);
	// 		$objActSheet->setCellValue('I'.$k, $v['alsobuy']); 
	// 		$objActSheet->getRowDimension($k)->setRowHeight(90);
	// 		$arr_time = explode(' ',$v['order_date']);
	// 		$time = $arr_time[0];
	// 		$now_time = date('Y-m-d',time());
	// 		if($time != $now_time){
	// 			$objActSheet->setCellValue('J'.$k, "***"); 
	// 		}else{
	// 			$objActSheet->setCellValue('J'.$k, " "); 
	// 		}
			
			
	// 		if(empty($v['remarks'])){
	// 			$objActSheet->setCellValue('K'.$k, "　"); 
	// 		}else{
	// 			$objActSheet->setCellValue('K'.$k, $v['remarks']); 
	// 		}
			
			
			
 //        }
 //        $fileName = '采购明细表';
 //        $date1 = date("Y-m-d",time());
 //        $fileName .= "_{$date1}.xls";

 //        $fileName = iconv("utf-8", "gb2312", $fileName);
 //        //重命名表
 //        // $objPHPExcel->getActiveSheet()->setTitle('test');
 //        //设置活动单指数到第一个表,所以Excel打开这是第一个表
 //        $objPHPExcel->setActiveSheetIndex(0);
 //        header('Content-Type: application/vnd.ms-excel');
 //        header("Content-Disposition: attachment;filename=\"$fileName\"");
 //        header('Cache-Control: max-age=0');

 //        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
 //        $objWriter->save('php://output'); //文件通过浏览器下载
 //        // END    
		
	// 	$porder_number = $this->StrOrderOne();
	// 	$where = " buyer='".$buyer."' and (status='2' or status='3') and is_create='' and sales_return='' and alsobuy>0";
	// 	//array('buyer'=>$buyer,'status'=>'2','is_create'=>'')
	// 	$result = M("order_info")->where($where)->save(array('is_create'=>'1','create_time'=>date('Y-m-d H:i:s'),'porder_number'=>$porder_number));
		
	// 	}
	// 	$now_time = date(('Y-m-d'),time());
	// 	$time = date(('Y-m-d'),time());
	// 	$now_start = $now_time. " 00:00:00";
	// 	$now_end = $now_time. " 59:59:59";
	// 	$this->assign("now_end",$now_end);
	// 	$this->assign("now_start",$now_start);
		
	// 	$this->assign("sum",sizeof($purchase_list));
	// 	$this->assign("type",$type);
	// 	$this->assign("count",$count);
	// 	$this->assign("create_time",$create_time);
	// 	$this->assign("purchase_list",$purchase_list);
	// 	$this->assign("purchase_list2",$purchase);
	// 	$this->assign("buyer_list",$buyer_list);
	// 	$this->display();
	// }
	
	 /**
     * 生成唯一订单号
     */
    static public function StrOrderOne(){
    /* 选择一个随机的方案 */
    mt_srand((double) microtime() * 1000000);
    return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}
	
	
	//采购单处理列表
 	public function purchase_note(){
		  
		$name = $_SESSION['user'];
		$type = M('account')->field('purchase')->where(array('username'=>$name))->find();
		if($type['purchase']=='2'){
			$where = "  is_create = '1' and buyer = '$name' and alsobuy>0";
			$order_list = M("order_info")->where($where)->group('porder_number')->order('create_time asc')->select();
			foreach($order_list as $k=>$v){
				$order_number = $v['order_number'];
				$result = M('order')->field('id')->where(array('buyer'=>$name,'order_number'=>$order_number))->SUM('quanqity');
				$order_list[$k]['o_id'] = $result[0]['id'];
				
			}
		}else{
			$where = " is_create = '1' and alsobuy>0";
			$order_list = M("order_info")->where($where)->group('porder_number')->order('create_time asc')->select();
			foreach($order_list as $k=>$v){
				$order_number = $v['order_number'];
				$result = M('order')->field('id')->where(array('order_number'=>$order_number))->select();
				$order_list[$k]['o_id'] = $result[0]['id'];
			}
		}
		$this->assign("order_list",$order_list);
		$this->display();
	}
	//历史采购单查询
	public function select_history_pur(){
		header("Content-type: text/html; charset=utf-8");
		$quanxian = M('account')->field('select')->where(array('username'=>$_SESSION['user']))->find();
		if(!$quanxian['select']){
			$this->assign('message','该用户暂无权限！');
			$this->display('error');exit;
		}
		//$where = '';//'status=2';//设置默认条件
		//判断GET参数
		$data['starttime'] = $_GET['delivery_time_start'];
		$data['endtime'] = $_GET['delivery_time_end'];
		$data['buyer'] = $_GET['buyer'];
		$pagesize = $_GET['pagesize']?$_GET['pagesize']:10;
		$nowpage = $_GET['page']?$_GET['page']:1;
		$limit = ''.($pagesize*$nowpage-$pagesize).','.$pagesize;
		$where = " finish_time!='0000-00-00 00:00:00' and finish_buyer !='' ";
		if(!empty($_GET)){
			//var_dump($_GET);
			$where .=  $_GET['delivery_time_start']?" and finish_time>='".$_GET['delivery_time_start']."'":'';
			$where .=  $_GET['delivery_time_end']?" and finish_time<='".$_GET['delivery_time_end']." 23:59:59'":'';
			$where .=  $_GET['buyer']?" and finish_buyer ='".$_GET['buyer']."'":'';
			
			$where = trim($where,' and');
		}
		$buyer_list = M('order_info')->field('buyer')->group('buyer')->select();
		//$count = M('order')->field('order.id,order.order_number,order_info.buyer,order.finish_time')->join('order_info on order.order_number=order_info.order_number')->where($where)->group('order_info.order_number')->order('order.id desc')->count();
		$count = M('finish_order')->field('id')->where($where)->count();
		//$count = M()->query("select count(xx.id) count from (SELECT order.id,order.porder_number,order_info.buyer,order.finish_time FROM `order` INNER JOIN order_info on order.order_number=order_info.order_number WHERE ".$where ." GROUP BY order_info.order_number ORDER BY order.finish_time desc) xx limit 1")[0]['count'];
		$countpage = ceil($count/$pagesize);
		/* 2017-04-28 chen */
		//$list = M('order')->field('order.id,order.order_number,order_info.buyer,order.finish_time,order.porder_number')->join('order_info on order.order_number=order_info.order_number')->where($where)->group('order_info.order_number')->order('order.id desc')->limit($limit)->select();
		/* 2017-04-28 chen */
		$list = M('finish_order')->field('id,porder_number,finish_buyer buyer,finish_time,porder_number,finish_order_number')->where($where)->order('finish_time  desc')->limit($limit)->select();
		$this->assign('data',$data);
		$this->assign('countpage',$countpage);
		$this->assign('nowpage',$nowpage);
		$this->assign('pagesize',$pagesize);
		$this->assign('count',$count);
		//var_dump($list);
		$this->assign('list',$list);
		$this->assign('buyer_list',$buyer_list);
		$this->display();

	}
	//获取批量导出id
	public function get_xxxxxx_id(){
		$where = " finish_time!='0000-00-00 00:00:00' and finish_buyer !='' ";
		$where .=  $_GET['start']?" and finish_time>='".$_GET['start']."'":'';
		$where .=  $_GET['end']?" and finish_time<='".$_GET['end']."'":'';
		$data = M('finish_order')->field('id')->where($where)->select();
		//var_dump($data);die;
		$str = '';
		foreach($data as $v){
			$str .=$v['id'].',';
		}
		if(trim($str)==''){
			$this->error('错误操作！');exit;
		}
		$url = U("export_download").'?source_page=select_history_pur&tids='.trim($str);
		header('Location:'.$url);
	}
	//历史采购单查询中的查看明细
	public function select_history_detailed(){
		// $p = M('account')->field('purchase')->where(array('username'=>$_SESSION['user']))->find()['purchase'];
		// if($p){
		// 	if($p!='1'){
		// 		if(!M('order_info')->field('id')->where(array('order_number'=>$_GET['order_info_id'],'buyer'=>$_SESSION['user']))->select()){
		// 			$this->error('该用户暂无权限！');exit;
		// 		}
		// 	}
		// }else{
		// 	$this->error('该用户暂无权限！');exit;
		// }
		$pagesize = $_GET['pagesize']?$_GET['pagesize']:10;
		$nowpage = $_GET['page']?$_GET['page']:1;
		$limit = ''.($pagesize*$nowpage-$pagesize).','.$pagesize;
		$porder_number = $_GET['porder_number'];
		$where = " porder_number = '$porder_number' and purchase_quantity>0";
		$count = M('finish_order_info')->field('id')->where($where)->count();
		$countpage = ceil($count/$pagesize);
		$list = M('finish_order_info')->field('id,supplier,sku,main_pic,cost_price purchase_price,quantity,purchase_quantity*cost_price total,purchase_quantity product_num,order_number,premarks')->where($where)->order('id desc')->limit($limit)->select();
		//var_dump(M()->getLastSql());
		$this->assign('list',$list);
		$this->assign('porder_number',trim($_GET['finish_order_number']));
		$this->assign('countpage',$countpage);
		$this->assign('nowpage',$nowpage);
		$this->assign('pagesize',$pagesize);
		$this->assign('count',$count);
		$this->display();

	}
	//编辑order_info保存方法
	public function order_info_save(){
		if(IS_AJAX){
			$q = M('account')->field('premarks')->where(array('username'=>$_SESSION['user']))->find();
			if(!$q['premarks']){
				echo json_encode(array('status'=>'1'));exit;
			}
			if(M('finish_order_info')->where(array('id'=>I('post.order_info_id',0,'intval')))->save(array('premarks'=>I('post.remarks','','strip_tags')))){
				echo json_encode(array('status'=>'3'));
			}else{
				echo json_encode(array('status'=>'2'));
			}
		}else{
			echo json_encode(array('status'=>'0'));
		}


	}
	public function export_download(){
		//$source_page = reset(explode('.',end(explode('/',$_SERVER['HTTP_REFERER']))));
		$source_page = trim($_GET['source_page']);
		//$source_page = $_GET['source_page']=='select_history_pur'?'历史采购':'历史采购明细';
		if($source_page=='select_history_pur'){
			$table = 'order';
			$title = array('完成时间','采购员','采购单号','供应商','SKU','采购单价','采购数量','总价','订单号','产品数量','备注');
			$data = M('finish_order')->field('finish_time,finish_buyer,finish_order_number,porder_number')->where(array('id'=>array('in',trim($_GET['tids'],','))))->order('id desc')->select();
			for($i=0;$i<count($data);$i++){
				$where = " porder_number = '".$data[$i]['porder_number']."' and purchase_quantity>0";
				$data[$i]['order_info']=M('finish_order_info')->field('supplier,sku,cost_price purchase_price ,purchase_quantity,purchase_quantity*cost_price total,order_number,quantity product_num,premarks')->where($where)->order('id desc')->select();
				//var_dump(M()->getLastSql());
				$data[$i]['porder_number']='';
			}
		}
		if($source_page=='select_history_detailed'){
			$title = array('供应商','SKU','采购单价','采购数量','总价','订单号','产品数量','备注');
			$data = M('order_info')->field('supplier,sku,purchase_price ,quantity,quantity*purchase_price total,order_number,quantity,premarks')->where(array('id'=>array('in',trim($_GET['tids'],','))))->order('id desc')->select();
		}
		/* 2017-04-28 chen */
		$title1 = array('供应商','SKU','采购单价','采购数量','总价','订单号','产品数量','备注');
		//var_dump($data);die;	
		$res = $this->exportexcel($data,$title,$source_page=='select_history_pur'?'历史采购':'历史采购明细',$title1);
		/* 2017-04-28 chen */

	}
	//导出xml
	public function exportexcel($data=array(),$title=array(),$filename='report',$title1){
		header("Content-type:application/octet-stream");
		header("Accept-Ranges:bytes");
		header("Content-type:applicationnd.ms-excel");  
		header("Content-Disposition:attachment;filename=".$filename.".xls");
		header("Pragma: no-cache");
		header("Expires: 0"); 
		
		/* 2017-04-28 chen */
		//导出xls 开始
		if (!empty($title)){
			foreach ($title as $k => $v) {
				$title[$k]=iconv("UTF-8", "GB2312",$v);
				//$title[$k]=$v;
			}
			$title= implode("\t", $title);
			echo "$title\n";
		}

		if (!empty($data)){
			
			//var_dump($data);die;
			foreach($data as $key=>$val){
				
				foreach ($val as $ck => $cv) {
					if($ck == 'order_info'){
						foreach($cv as $k => $v){
							echo "\n\t\t\t";
							foreach($v as $ke => $va){
								echo iconv("UTF-8", "GB2312", $va)."\t";
							}
						}
					}else{
						echo iconv("UTF-8", "GB2312", $cv)."\t";
						
					}

				}
				echo "\n";


			}
			//echo implode("\n",$cv);
		}
		/* 2017-04-28 chen */
		/*if (!empty($data)){
			foreach($data as $key=>$val){
				foreach ($val as $ck => $cv) {
					$data[$key][$ck]=iconv("UTF-8", "GB2312", $cv);
				}
				$data[$key]=implode("\t", $data[$key]);
				
			}
			echo implode("\n",$data);
		}*/
		
	}
	//历史采购单查询中的删除链接
	public function select_history_delete(){
		$order ='finish_order';
		$id = I('get.order_id',0,'intval');
		//查询该用户是否有删除权限
		$p = M('account')->field('del_history')->where(array('username'=>$_SESSION['user']))->find();
		if(!$p['del_history']){
			$this->error('该用户暂无权限！');exit;
		}
		if(M($order)->field('id')->where(array('id'=>$id))->select()){
			if(M($order)->where(array('id'=>$id))->delete()){
				$this->success('删除成功！',U('Purchase/select_history_pur'));exit;
			}else{
				$this->error('删除失败！', U('Purchase/select_history_pur'));exit;
			}
		}else{
			$this->error('数据不存在！请输入正确数据', U('Purchase/select_history_pur'));
		}
			
		
	}
	
	//采购单处理 采购明细表
	public function purchase_details(){
		$name = $_SESSION['user'];
		$type = M('account')->field('purchase')->where(array('username'=>$name))->find();
		$porder_number = I('get.porder_number','','htmlspecialchars');
		if($type['purchase']=='2'){

			$where = " porder_number = '$porder_number' and buyer='$name' and is_create = '1' and sales_return=''  and alsobuy >0";
			$order_list = M('order_info')->where($where)->order('supplier asc,sku asc')->select();	
			
		}else{

			$where = " porder_number = '$porder_number' and is_create = '1' and sales_return=''  and alsobuy >0";
			$order_list = M('order_info')->where($where)->order('supplier asc,sku asc')->select();
		
		}

		$now_time = date(('Y-m-d'),time());
		if(I('post.edit','','htmlspecialchars')){
			if(I('post.edit','','htmlspecialchars')=='2'){
				 foreach($order_list as $val){
				 	$purchase_quantity = $val['quantity']-$val['cumulative_quantity']; 	
				 	$result = M('order_info')->where(array('id'=>$val['id']))->save(array('purchase_quantity'=>$purchase_quantity));
				 }
			}
			// $order_ids = I('post.order_ids','','htmlspecialchars');
			// $quantity = I('post.quantity','','htmlspecialchars');
			// $purchase_quantity = I('post.purchase_quantity','','htmlspecialchars');
			// $cumulative_quantity = I('post.cumulative_quantity','','htmlspecialchars');
			// $remarks = I('post.remarks','','htmlspecialchars');
			// $alsobuy = I('post.alsobuy','','htmlspecialchars');
			// $cost_price = I('post.cost_price','','htmlspecialchars');
			// foreach($order_ids as $key=>$val){
			// 	foreach($_POST['price_sku'] as $k => $v){
			// 		if($v == $_POST['cost_sku'][$key]){
			// 			$jiage = $_POST['cost_price'][$k];
			// 			break;
			// 		}
			// 		continue;
			// 	}
			// 	$info = M('order_info')->field('quantity,sku,porder_number')->where(array('id'=>$val))->find();
			// 	$total_cost = $info['quantity']*$jiage;
			// 	$res = M('order_info')->where(array('sku'=>$info['sku'],'porder_number'=>$info['porder_number']))->select();
			// 	$result = M('order_info')->where(array('sku'=>$info['sku'],'porder_number'=>$info['porder_number']))->save(array('purchase_quantity'=>$purchase_quantity[$key],'remarks'=>$remarks[$key],'cost_price'=>$jiage,'total_cost'=>$total_cost));
				
			// }
			$this->success("修改成功");exit;
		}
		foreach($order_list as $k => $v){
				$quantity = M('order_info')->where(array('porder_number'=>$porder_number,'is_create'=>'1','sku'=>$v['sku']))->order('sku')->SUM('quantity');
				$cumulative_quantity = M('order_info')->where(array('porder_number'=>$porder_number,'is_create'=>'1','sku'=>$v['sku']))->order('supplier asc,sku asc')->SUM('cumulative_quantity');
			
				$order_list[$k]['count'] = $quantity-$cumulative_quantity;
		}
		
		$now_time = date(('Y-m-d'),time());
		$time = date(('Y-m-d'),time());
		$now_start = $now_time. " 00:00:00";
		$now_end = $now_time. " 59:59:59";
		$this->assign("now_end",$now_end);
		$this->assign("now_start",$now_start);
		
		$this->assign('porder_number',$porder_number);
		$this->assign('order_list',$order_list);
		$this->assign("now_time",$now_time);
		$this->display();
	}

	public function dbclick_edit(){
		$id = I('post.id','','htmlspecialchars');
		$sku = I('post.sku','','htmlspecialchars');
		$name = I('post.name','','htmlspecialchars');
		$value = I('post.value','','htmlspecialchars');
		$porder_number	= I('post.porder_number','','htmlspecialchars');
		if($name=='cost_price'){
			$list = M('order_info')->field('quantity,id')->where(array('sku'=>$sku))->order('supplier asc,sku asc')->select();
			foreach($list as $val){
				$total_cost = $val['quantity']*$value;
				$result = M('order_info')->where(array('id'=>$val['id']))->save(array('cost_price'=>$value,'total_cost'=>$total_cost));
			}
		}else if($name=='purchase_quantity'){

			$result = M('order_info')->where(array('id'=>$id))->save(array('purchase_quantity'=>$value));
			

		}else if($name=='remarks'){

			$result = M('order_info')->where(array('id'=>$id))->save(array('remarks'=>$value));
			//echo M('order_info')->getLastSql();die;

		}
		echo 'success';exit();
		

		// $info = M('order_info')->field('quantity,sku,porder_number')->where(array('id'=>$val))->find();

		// $total_cost = $info['quantity']*$jiage;
		// $res = M('order_info')->where(array('sku'=>$info['sku'],'porder_number'=>$info['porder_number']))->select();
		// $result = M('order_info')->where(array('sku'=>$info['sku'],'porder_number'=>$info['porder_number']))->save(array('purchase_quantity'=>$purchase_quantity[$key],'remarks'=>$remarks[$key],'cost_price'=>$jiage,'total_cost'=>$total_cost));

	}
	
	//采购单处理完成
	public function purchase_finish(){	
		$porder_number = I("get.porder_number","","htmlspecialchars");

		/*$res = M('order_info')->field('buyer,sku,order_number,purchase_quantity,quantity,id,cumulative_quantity')->where(array('porder_number'=>$porder_number))->order('order_number')->select();*/
		$res = M('order_info')->field('*')->where(array('porder_number'=>$porder_number))->order('order_number')->select();
		
		/*chen 2017-04-28*/
		// $date = date("Y-m-d",time());
		// $where= "buyer = '".$res[0]['buyer']."' and finish_time like '".$date."%'";

		// $count = M('order_info') -> field('id')  -> where($where) -> group('order_number') -> select();
		// $count = count($count)+1;
		// if($count<10){
		// 	$count = "0".$count;
		// }
		$count = rand(1111,9999);
		$date = date("YmdHis",time());
		$data['porder_number'] = $porder_number;
		$data['finish_order_number'] = $res[0]['buyer'].$date.$count;
		$data['finish_buyer'] = $res[0]['buyer'];
		
		unset($where);
		$where['order_number'] = $res[0]['order_number'];
		
		$data['finish_time'] = date("Y-m-d H:i:s",time());
		$is_save = 0;

		

		/*chen 2017-04-28*/

		$time = date('Y-m-d H:i:s');
		foreach($res as $val){		//循环该份采购单内的所有信息
			$vals = $val;
			if($vals['purchase_quantity']>0){
				if(!$is_save){
					//var_dump($is_save);
					$res = M('finish_order')->data($data)->add();
					if($res){
						$is_save = 1;
					}
				}
				unset($vals['id']);
				$val['finish_time'] = $time;
				M('finish_order_info')->data($vals)->add();
			}
			if($val['cumulative_quantity']+$val['purchase_quantity']<$val['quantity']){		//如果累计购买的数量加上新提交的数量小于需要采购的数量
				$cumulative_quantity = $val['purchase_quantity']+$val['cumulative_quantity'];		//则累计数量为原有的采购数量加现提交的数量
				$alsobuy = $val['quantity']-$val['purchase_quantity']-$val['cumulative_quantity'];	//还需采购的数量为该产品所需要的数量减提交的数量和原累计购买的数量
				$result = M('order_info')->where(array('id'=>$val['id']))->save(array('is_create'=>'','porder_number'=>null,'purchase_quantity'=>'','cumulative_quantity'=>$cumulative_quantity,'alsobuy'=>$alsobuy,'purchase_quantity'=>'','finish_time'=>$time));
			}else{			//如果购买多了
			
				$cumulative_quantity = $val['purchase_quantity']+$val['cumulative_quantity'];		
				$alsobuy = $val['quantity']-$val['purchase_quantity']-$val['cumulative_quantity'];
				$result = M('order_info')->where(array('id'=>$val['id']))->save(array('status'=>'2','cumulative_quantity'=>$cumulative_quantity,'alsobuy'=>$alsobuy,'purchase_quantity'=>'0'));
				/*if(!$is_save){
					var_dump($is_save);
					$res = M('finish_order')->data($data)->add();
					if($res){
						$is_save = 1;
					}
				}*/
			}
			
		}
		$this->success("处理成功！");exit();

	}

	//采购单删除
	public function purchase_dele(){
		$porder_number = I("get.porder_number","","htmlspecialchars");
		$res = M('order_info')->field('id,order_number,purchase_quantity')->where(array('porder_number'=>$porder_number,'sales_return'=>''))->select();
		foreach($res as $val){
			if($val['purchase_quantity']!='0'){
				$res = M('order_info')->where(array('id'=>$val['id']))->save(array('sales_return'=>1));
				$result = M('order')->where(array('order_number'=>$val['order_number']))->save(array('sales_return'=>1));
			}else{
				$res = M('order_info')->where(array('id'=>$val['id']))->delete();
			}
		}
		
		header("Location:".$_SERVER['HTTP_REFERER']);
		
	}
	
	
	
	//退货汇总
	public function goods_returned_list(){
		$pageNo=empty($_REQUEST['pageNo'])?1:$_REQUEST['pageNo'];
		$pageSize=empty($_REQUEST['pageSize'])?10:$_REQUEST['pageSize'];
		$clear = M('sales_return')->where(array('quantity'=>0))->delete();
		
		$name = $_SESSION['user'];
		$type = M('account')->field('purchase')->where(array('username'=>$name))->find();
		if($type['purchase']!='1'){
			$list_count = M('sales_return')->where("buyer = $name and quantity>0")->select();
			$list = M('sales_return')->where("buyer = $name and quantity>0")->limit(($pageNo-1)*$pageSize,$pageSize)->select();
		}else{
			$list_count = M('sales_return')->where("quantity>0")->select();
			$list = M('sales_return')->where("quantity>0")->limit(($pageNo-1)*$pageSize,$pageSize)->select();
		}
		
		
		if(I('post.deleAll','','htmlspecialchars')){
			$tid = I('ids','','htmlspecialchars');
			foreach($tid as $val){
				$list = M('order_info')->where(array('sales_return'=>'1','id'=>$val))->delete();
				header("Location:".$_SERVER['HTTP_REFERER']);
			}
		}
		
		
		$count['count'] = count($list_count);
		$count['pageNo'] = $pageNo;
		$count['pageSize'] = $pageSize;
		
		$count['countpage']=ceil($count['count']/$pageSize);
		
		$this->assign('count',$count);
		$this->assign('list',$list);
		$this->display();	
	}
	
	
	//单个删除退货数据
	public function return_dele(){
		$info_id = I('get.id','','htmlspecialchars');
		$list = M('order_info')->where(array('id'=>$info_id))->delete();
		$list2 = M('sales_return')->where(array('info_id'=>$info_id))->delete();
		$this->success('退货成功！');
		
	}
	
	//批量删除退货数剧 
	public function return_deleAll(){
		$ids=I("get.tids",'','htmlspecialchars');
		$id_list = explode(',',trim($ids,','));
		foreach($id_list as $val){
			$list = M('order_info')->where(array('id'=>$val))->delete();
			$list2 = M('sales_return')->where(array('info_id'=>$val))->delete();
		}
		$this->success('退货成功！');exit();
	}
	
	
}